package 多线程.消费者生产者;

import javafx.print.Printer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Print1 {
    public static void main(String[] args) {
        Printer1 p = new Printer1();
        new Thread(()->{
            p.printOdd();
        },"偶数").start();
        new Thread(()->{
            p.printEven();
        },"奇数").start();
    }

}


class Printer1{
    private static volatile int count = 0;

    Lock lock = new ReentrantLock();
    Condition con = lock.newCondition();
    public void printEven(){
        try{
            lock.lock();
            while(count<100){
                while(count%2!=1){
                    con.await();
                }
                System.out.println(Thread.currentThread().getName()+":"+count);
                count++;
                con.signal();
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printOdd(){
        try{
            lock.lock();
            while(count<100){
                while(count%2!=0){
                    con.await();
                }
                System.out.println(Thread.currentThread().getName()+":"+count);
                count++;
                con.signal();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}
